<template>
  <div class="wrapper">
    <!--头部-->
    <header>
      <i @click="goBack()" class="fa fa-angle-left"></i>
      <p>在线支付</p>
    </header>
    <!--订单信息-->
    <h3>订单信息：</h3>
    <div class="order-info">
      <p>
        {{ orders.business.businessName }}
        <i class="fa fa-caret-down" @click="detailedShow"></i>
      </p>
      <p>
        &yen; {{ this.pickedCredit ? (this.orders.orderTotal - this.usableCredit * 0.01 >= 0 ? this.orders.orderTotal - this.usableCredit * 0.01 : 0)
          : this.orders.orderTotal
        }}
      </p>
    </div>
    <!--订单明细-->
    <ul class="order-detailed" v-show="isShowDetailed">
      <li v-for="item in orders.list">
        <p>{{ item.food.foodName }} × {{ item.quantity }}</p>
        <p>&yen;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&yen;{{ orders.business.deliveryPrice }}</p>
      </li>
    </ul>
    <!--支付方式-->
    <ul class="payment-type">
      <li>
        <img src="../assets/img/payment/微信支付.svg" for="weixin">
        <input type="radio" id="weixin" v-model="pay_method" value="weixin" checked />
      </li>
      <li>
        <img src="../assets/img/payment/支付宝支付.svg" for="zhifubao">
        <input type="radio" id="zhifubao" v-model="pay_method" value="zhifubao" />
      </li>
      <li>
        <div>
          <img src="../assets/img/payment/e币支付.svg" for="elm">
          剩余:{{ wallet.balance }}
        </div>
        <input type="radio" id="elm" v-model="pay_method" value="elm" checked />
      </li>
    </ul>
    <div class="payment-button">
      <button :style="pay_method ? 'background-color:#38CA73' : 'background-color: #999'" @click="toPay()">
        确认支付
      </button>
    </div>


    <div id="credit" class="form-check">
      <input class="form-check-input" type="checkbox" value="picked" v-model="pickedCredit" id="credit-checkbox">
      <label class="form-check-label" for="credit-checkbox">
        拥有{{ usableCredit }}积分，
        本单可用{{ (orders.orderTotal - usableCredit * 0.01 >= 0) ? usableCredit : orders.orderTotal * 100 }}积分，
        抵扣{{ (orders.orderTotal - usableCredit * 0.01 >= 0) ? (usableCredit * 0.01).toFixed(2) : orders.orderTotal }}元
      </label>
    </div>

    <!--底部菜单-->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/Footer";
export default {
  name: "Payment",
  data() {
    return {
      orderId: this.$route.query.orderId,

      user: {},
      wallet: {},
      orders: {
        business: {}
      },
      isShowDetailed: true,
      usableCredit: '',

      // v-model绑定属性
      pay_method: '',
      pickedCredit: '',
    }
  },
  created() {
    this.user = this.$getSessionStorage('user');

    // 获取当前用户的wallet
    this.$axios.get(`VirtualWalletController/getWallet/${this.user.userId}`
    ).then(response => {
      this.wallet = response.data.result;
      // console.log(this.wallet)
    }).catch(error => {
      console.error(error);
    });

    // 获取当前用户的订单
    this.$axios.get(`OrdersController/getOrdersById/${this.orderId}`
    ).then(response => {
      this.orders = response.data.result;

    }).catch(error => {
      console.error(error);
    });

    // 获取当前用户的积分
    this.$axios.get(`CreditController/getUsableCredit/${this.user.userId}`
    ).then(response => {
      this.usableCredit = response.data.result;
    }).catch(error => {
      console.error(error);
    });


  },
  mounted() {

    //一旦路由到在线支付组件，就不能再回到订单确认组件
    //现将当前url添加到history对象中
    // history.pushState(null, null, document.URL);
    //popstate事件能够监听history对象的变化
    window.onpopstate = () => {
      this.goBack();
    }
  },
  destroyed() {
    window.onpopstate = null;
  },

  components: {
    Footer
  },

  methods: {
    goBack() {
      // alert('订单已生成，将返回商家界面');
      this.$router.push({ path: '/index' });
    },
    detailedShow() {
      this.isShowDetailed = !this.isShowDetailed;
    },
    toPay() {

      if (this.pay_method == 'elm') {
        // 判断当前余额是否能支付
        if (this.wallet.balance < this.orders.orderTotal) {
          alert('当前所剩e币不够支付');
          return;
        }

        // 扣取用户积分
        if (this.pickedCredit) {
          let url = `CreditController/ordersUseDiscount/${this.user.userId}`
          this.$axios.put(url).then(response => {
            if (response.data.result > 0)
              this.orders.orderTotal = this.pickedCredit ? (this.orders.orderTotal - this.usableCredit * 0.01 >= 0 ? this.orders.orderTotal - this.usableCredit * 0.01 : 0)
                : this.orders.orderTotal;
          })
        }


        // 改变订单状态，从用户钱包扣费
        let paymentAmount = (this.pickedCredit ? (this.orders.orderTotal - this.usableCredit * 0.01 >= 0 ?
          this.orders.orderTotal - this.usableCredit * 0.01 : 0) : this.orders.orderTotal)
        let url = `VirtualWalletController/wallets/${this.wallet.walletId}/orderId/${this.orderId}/userId/${this.user.userId}/paymentAmount/${paymentAmount}`
        this.$axios.put(url).catch(error => {
          console.error(error);
        });

        // 扣费成功，给用户增加相应积分
        if (this.pickedCredit == '') {
          let url = `CreditController/ordersAddCredit/${this.user.userId}/${this.orders.orderDate}/${this.orders.orderTotal}`
          this.$axios.put(url).catch(error => {
            console.error(error);
          });
        }
        alert("支付成功");
        this.$router.push({ path: '/index' });

      } else if (this.pay_method == 'weixin' || this.pay_method == 'zhifubao') {
        alert("微信/支付宝支付暂不支持");
      }
      else {
        alert("请先选择支付方式")
      }
    },
    // computed: {
    //   totalSettle() {
    //     return this.pickedCredit ? (this.orders.orderTotal - this.usableCredit * 0.01 >= 0 ? this.orders.orderTotal - this.usableCredit * 0.01 : 0)
    //       : this.orders.orderTotal

    //   }
    // },
  }
}
</script>

<style scoped>
/**************************总容器**************************/
.wrapper {
  width: 100%;

}

/**************************header**************************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #FFF;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;
}

/**************************订单信息**************************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw 4vw 0;

  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order-info {
  box-sizing: border-box;
  padding: 4vw;

  font-size: 4vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-info p:last-child {
  color: orangered;
}

/**************************订单明细**************************/
.wrapper .order-detailed {
  width: 100%;
}

.wrapper .order-detailed li {
  box-sizing: border-box;
  padding: 1vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-detailed li p {
  font-size: 3vw;
  color: #666;
}

/**************************支付方式**************************/
.wrapper .payment-type {
  width: 92%;
  margin-left: 4%;
}

.wrapper .payment-type li {
  width: 100%;
  margin-top: 1.8vw;
  box-sizing: border-box;
  border: 2px solid rgb(235, 235, 235);
  border-radius: 12px;
  padding: 2.5vw;
  background-color: rgb(245, 247, 247);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .payment-type li img {
  width: 22vw;
  height: 8.9vw;
}

.wrapper .payment-type input {
  width: 4vw;
  height: 4vw;
}

.wrapper .payment-type li .fa-circle {
  font-size: 5vw;
  color: rgb(175, 170, 170);
}

.wrapper .payment-type li .fa-check-circle {
  font-size: 5vw;
  color: #38CA73;
}

.wrapper .payment-button {
  font-size: 4vw;
  width: 100%;
  box-sizing: border-box;
  padding: 4vw;
}

.wrapper .payment-button button {
  width: 100%;
  height: 12vw;
  margin: 4vw auto 0;
  border: none;
  /*去掉外轮廓线*/
  outline: none;
  border-radius: 6px;
  background-color: #38CA73;
  color: #fff;
}

.wrapper #credit {
  width: 86vw;
  font-size: 3.3vw;
  margin: 0 7vw;
}
</style>